package minio;

import io.minio.MinioAsyncClient;
import io.minio.admin.MinioAdminClient;
import minio.client.MinioAsyncClientX;
import minio.client.MinioTemplate;
import minio.client.MinioWebTemplate;
import minio.properties.MinioProperties;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnNotWebApplication;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;

@AutoConfiguration
@EnableConfigurationProperties(MinioProperties.class)
class MinioAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean
    MinioAsyncClientX minioAsyncClient(MinioProperties minioProperties) {
        MinioAsyncClient minioAsyncClient = MinioAsyncClient.builder()
                .endpoint(minioProperties.getUrl())
                .credentials(minioProperties.getAccessKey(), minioProperties.getSecretKey())
                .build();
        return new MinioAsyncClientX(minioAsyncClient);
    }

    @Bean
    @ConditionalOnMissingBean
    @ConditionalOnNotWebApplication
    MinioTemplate minioTemplate(MinioProperties minioProperties, MinioAsyncClientX minioAsyncClient) {
        return new MinioTemplate(minioProperties.getBucketName(), minioAsyncClient);
    }

    @Bean
    @ConditionalOnMissingBean
    @ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
    MinioWebTemplate minioWebTemplate(MinioProperties minioProperties, MinioAsyncClientX minioAsyncClient) {
        return new MinioWebTemplate(minioProperties.getBucketName(), minioAsyncClient);
    }

    @Bean
    @ConditionalOnMissingBean
    @ConditionalOnProperty(value = "minio.enable-admin-client", havingValue = "true")
    MinioAdminClient minioAdminClient(MinioProperties minioProperties) {
        return MinioAdminClient.builder()
                .endpoint(minioProperties.getUrl())
                .credentials(minioProperties.getAdminAccessKey(), minioProperties.getAdminSecretKey())
                .build();
    }
}